﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace FisheryPlatform.Search.Core.Resource
{
    /// <summary>
    /// 路径类,能将定制的路径解析成真实物理路径
    /// </summary>
    public class CentralPath
    {
        public static readonly Regex ApplicationRegex = new Regex(@"\$\{[a-z]+\}");
        
        public static Dictionary<string, string> PathVar = new Dictionary<string, string>();

        static CentralPath()
        {
            foreach (string key in ConfigurationManager.AppSettings.Keys)
            {
                if (!ApplicationRegex.IsMatch(key))
                    continue;
                string value = ConfigurationManager.AppSettings[key];
                PathVar.Add(key, value);
            }
        }

        private string _path;

        public CentralPath(string path, bool create) 
        {
            _path = GetRealPath(path, create);
        }
    
        public CentralPath(string path) : this(path, false)
        {
        }
        /// <summary>
        /// 隐含操作方法,能将CentralPath转换成string
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static implicit operator string(CentralPath path)
        {
            return path.ToString();
        }
        /// <summary>
        /// 重载ToString,返回真实的物理路径
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return _path;
        }

        private static string GetRealPath(string path, bool create)
        {
            var uri = new CustomUri(path);
            string file = Path.GetFileName(path);
            var factory = new CentralPathResourceFactory();
            if (!create)
            {
                var rc = factory.Create(uri);
                return Path.Combine(rc.FileBasePath, file);
            }
            return Path.Combine(CentralPathResourceFactory.GetBasePath(), uri.Host + uri.Path);
        }
    }
}
